/* eslint-disable no-use-before-define */
import { defineComponent, ref, onMounted, SetupContext } from 'vue';
import { inputBtnsProps, InputBtnsProps } from './props/input-btns.props';

export default defineComponent({
    name: 'InputBtns',
    props: inputBtnsProps,
    emits: [] as string[] | undefined,
    setup(props: InputBtnsProps, context: SetupContext) {
        // 注册事件并清空待注册列表
        const eventHooks: (() => void)[] = [];
        function calculate(event: MouseEvent | TouchEvent): void {
            event.preventDefault();
            calculateCoordinates(event);
        }
        function removeListeners(): void {
            eventHooks.forEach((cb) => cb());
            eventHooks.length = 0;
        }
        function onEventChange(event: MouseEvent | TouchEvent): void {
            calculate(event);
            document.addEventListener('mouseup', removeListeners);
            document.addEventListener('touchend', removeListeners);
            // document.addEventListener('mousemove', calculate);
            document.addEventListener('touchmove', calculate);
        }
        const handleOnClick = (event: any) => {
            onEventChange(event);
        };

        onMounted(() => {
            const targetElements = document.querySelectorAll('.f-input-btns-component');
            targetElements.forEach((element) => {
                element.addEventListener('mousedown', handleOnClick);
                element.addEventListener('touchstart', handleOnClick);
            });
        });

        function calculateCoordinates(event: MouseEvent | TouchEvent): void {
            const elementRef = document.querySelector('.f-input-btns-component');
            if (elementRef) {
                const { width: elWidth, height: elHeight, top: elTop, left: elLeft } = elementRef.getBoundingClientRect();

                const { pageX, pageY } = 'touches' in event ? event.touches[0] : event;

                const x = Math.max(0, Math.min(pageX - (elLeft + window.pageXOffset), elWidth));
                const y = Math.max(0, Math.min(pageY - (elTop + window.pageYOffset), elHeight));

                movePointer();
            }
        }

        function movePointer(): void {}
        return () => (
            <div class="f-input-btns-component">
                <div>
                    <input type="text" placeholder="cs" />
                </div>
            </div>
        );
    }
});
